#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <errno.h>

int main(int argc, char* argv[]){
    int fd, ret;
    int key_val;
    fd_set readfds;
    struct timeval timout;

    if (argc != 2) {
        printf("input number error!\n");
        return -1;
    }

    fd = open(argv[1], O_RDONLY | O_NONBLOCK);
    if (fd < 0) {
        printf("open file error\n");
        return -1;
    }

    while (1) {
        FD_ZERO(&readfds);       // 每次循环重新初始化
        FD_SET(fd, &readfds);    // 重新设置文件描述符
        timout.tv_sec = 1;       // 设置超时为 100ms
        timout.tv_usec = 0;

        ret = select(fd + 1, &readfds, NULL, NULL, &timout);
        printf("ret: %d \n", ret);

        switch(ret) {
            case 0:  // 超时
                printf("case 0 (timeout)\n");
                break;
            case -1: // 错误
                perror("select error");
                break;
            default:
                if (FD_ISSET(fd, &readfds)) {
                    ret = read(fd, &key_val, sizeof(int));
                    if (ret < 0) {
                        if (errno == EAGAIN) {
                            printf("No data available (non-blocking)\n");
                        } else {
                            perror("read error");
                        }
                        continue;
                    }
                    if (0 == key_val) printf("key press\n");
                    else if (key_val == 1) printf("key release\n");
                }
                break;
        }
    }

    close(fd);
    return 0;
}